package com.plum.admin.config.security.filter;

import cn.hutool.core.util.StrUtil;
import com.plum.admin.common.exception.CodeValidateException;
import com.plum.admin.common.exception.LoginFailLimitException;
import com.plum.admin.common.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/8/13 14:35
 */
@Component
@Slf4j
public class AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Value("${token.loginTimeLimit}")
    private Integer loginTimeLimit;
    @Value(("${token.loginAfterTime}"))
    private Long loginAfterTime;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        if(e instanceof UsernameNotFoundException|| e instanceof BadCredentialsException){
            String username = request.getParameter("username");
            computeFailTime(username);
            String key = "loginTimeLimit:" + username;
            String value = redisTemplate.opsForValue().get(key);
            if (StrUtil.isBlank(value)) {
                value = "0";
            }
            int loginFailTime = Integer.parseInt(value);
            int restLoginTime = loginTimeLimit - loginFailTime;
            log.info("用户" + username + "登录失败，还有" + restLoginTime + "次机会");
            if (restLoginTime <= loginTimeLimit && restLoginTime > 0) {
                ResponseUtil.out(response, ResponseUtil.resultMap(500, "用户名或密码错误，还有" + restLoginTime + "次尝试机会"));
            } else if (restLoginTime <= 0) {
                ResponseUtil.out(response, ResponseUtil.resultMap(500, "登录错误次数超过限制，请" + loginAfterTime + "分钟后再试"));
            } else {
                ResponseUtil.out(response, ResponseUtil.resultMap( 500, "用户名或密码错误"));
            }
        }else if(e instanceof DisabledException){
            ResponseUtil.out(response,ResponseUtil.resultMap(500,"账户被禁用，请联系管理员"));
        }else if(e instanceof LoginFailLimitException){
            ResponseUtil.out(response,ResponseUtil.resultMap(500,((LoginFailLimitException) e).getMsg()));
        }else if(e instanceof CodeValidateException){
            ResponseUtil.out(response,ResponseUtil.resultMap(500,e.getMessage()));
        }else{
            ResponseUtil.out(response,ResponseUtil.resultMap(500,"系统内部错误"));
        }
    }
    private void computeFailTime(String username){
        String key = "loginTimeLimit:" + username;
        String flagKey = "loginFailFlag:" + username;
        String value = redisTemplate.opsForValue().get(key);
        if(StrUtil.isBlank(value)){
            value="0";
        }
        Integer count=Integer.parseInt(value)+1;
        redisTemplate.opsForValue().set(key,count.toString(),loginAfterTime, TimeUnit.MINUTES);
        if(count>loginTimeLimit){
            redisTemplate.opsForValue().set(flagKey,"fail",loginAfterTime, TimeUnit.MINUTES);
        }
    }
}
